import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Divider, Table, Upload, Row, Col, Input } from 'antd';
import '@/assets/css/settings';
import * as ApplyAcceptance from '../../axios/ApplyAcceptance'
import * as APIService from '../../axios/api'
import { baseUrl } from '../../config'
import { BasicLayout, BasicLayoutSearch } from '../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../components/TableCustomize'
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import AddForm2 from './AddForm2';
import AddFormPromise from './AddFormPromise';
import moment from 'moment';
import ProductionForm from './ProductionForm';
import { withRouter } from 'react-router';
import { withPermission } from '../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DeleteButton = withPermission(Button, 'delete')
const CheckButton = withPermission(Button, 'check')
const UploadButton = withPermission(Button, 'upload')
const CloseButton = withPermission(Button, 'minus')
const { confirm } = Modal;
const FormItem = Form.Item;
class Apply extends Component {
    state = {
        dataSource: [],
        visible: false,
        advanced: false,
        searchItem: {},

        formData: {},
        drawerVisible: false,
        drawerTitle: '新增',
        pageSize: 10,
        pageNum: 1,
        total: 0,
        operateType: 0,
        selectedRowKeys: [],
        selectedRows: [],
        columns: [
            {
                title: '序号',
                dataIndex: 'dataIndex',
                align: 'center',
                width: 50,
                render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
            },
            {
                title: '生产批号',
                dataIndex: 'batchNo',
                width: 150,
                sorter: (a, b) => compareString(a.batchNo, b.batchNo)
            },

            {
                title: '产品机型',
                width: 180,
                dataIndex: 'productModelName',
                sorter: (a, b) => compareString(a.productModelName, b.productModelName),
            },
            {
                title: '验收状态',
                // width: 100,
                // allowEllipsis: true,
                dataIndex: 'statusValue',
                sorter: (a, b) => compareString(a.statusValue, b.statusValue)
            },

            {
                title: '期望验收时间',
                // width: 100,
                // allowEllipsis: true,
                dataIndex: 'acceptanceHopeTime',
                sorter: (a, b) => compareString(a.acceptanceHopeTime, b.acceptanceHopeTime)
            },
            {
                title: '验收时间',
                // width: 100,
                // allowEllipsis: true,
                dataIndex: 'acceptanceStartTime',
                sorter: (a, b) => compareString(a.acceptanceStartTime, b.acceptanceStartTime)
            },
            {
                title: '完成时间',
                // width: 100,
                // allowEllipsis: true,
                dataIndex: 'acceptanceEndTime',
                sorter: (a, b) => compareString(a.acceptanceEndTime, b.acceptanceEndTime)
            },
            {
                title: '授权账号',
                // width: 100,
                dataIndex: 'empowerNames',
                sorter: (a, b) => compareString(a.empowerNames, b.empowerNames),

            },
            {
                title: '操作',
                width: 280,
                dataIndex: 'opts',
                align: 'center',
                render: (text, record) => <>
                    {/* <a onClick={() => this.openTGXX(record)}>视频</a> */}
                    {/* <Divider type="vertical" /> */}
                    <a onClick={() => this.openDetail(record)}>技术协议</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.kaidan(record)}>授权</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.check(record)}>验收</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.openModel(record, 1)}>修改</a>
                    {
                        record.status === 0 ? <span><Divider type="vertical" />
                            <a onClick={() => this.remove(record.id)}>删除</a></span> : ''
                    }

                </>
            },

        ],
        ModelList: [],
        pagination: {
            pageNum: 1,
            pageSize: 10
        },
        columnsModel: [
            {
                title: '序号',
                dataIndex: 'x_',
                width: 60,
                render: (text, record, index) => {
                    return (
                        `${(this.state.pagination.pageNum - 1) * (this.state.pagination.pageSize) + (index + 1)}`
                    )
                }
            },
            {
                title: '机型编码',
                dataIndex: 'code',
                key: 'code',
                // width: 100,
                ellipsis: true,
                // sorter: (a, b) => compareString(a.productNamee, b.productNamee),

            },
            {
                title: '机型名称',
                dataIndex: 'attributeFirst',
                key: 'attributeFirst',
                // width: 100,
                ellipsis: true,
                // sorter: (a, b) => compareString(a.productNamee, b.productNamee),
            },
            {
                title: '加工部门',
                dataIndex: 'assemblyWorker',
                key: 'assemblyWorker',
                // width: 100,
                ellipsis: true,
                // sorter: (a, b) => compareString(a.productNamee, b.productNamee),
            },
        ],
        visibleModel: false,
        drawerVisible1: false,
        drawerTitle1: '验收文档上传',
        formData1: {},
        personList: {},
        promiseView: false,
        promiseTitle: '授权',
        formDatapromise: {},
        checkVisible: false,
        checkRow: {},
        fileList: []
    };
    componentDidMount() {
        this.fetch();
        this.queryCondition()
        this.getList()
    }
    queryCondition = (pageNum = 1, pageSize = 10) => {
        let params = {
            pageNum,
            pageSize
        }
        ApplyAcceptance.queryByCondition(params).then(res => {
            this.setState({ loading: false })
            // console.log('列表', res)
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg)
                return
            }
            this.setState({
                ModelList: res.data.data.data,
                model_total: res.data.data.total,
                pagination: { pageNum: res.data.data.pageNum, pageSize: res.data.data.pageSize },
            })
        }).catch(err => {
            openModalMessage('error', err.data.message)
        })
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 10) => {
        this.setState({ loading: true })
        const { searchItem } = this.state
        searchItem.pageNum = pageNum
        searchItem.pageSize = pageSize

        ApplyAcceptance.queryByPage(searchItem).then(res => {
            this.setState({ loading: false })
            console.log('列表', res)
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg)
                return
            }
            this.setState({
                dataSource: res.data.data,
                total: res.data.total,
                pageNum: res.data.pageNum,
                pageSize: res.data.pageSize,
                selectedRowKeys: [],
                selectedRows: [],
                row: []
            })
        }).catch(err => {
            // openModalMessage('error', err.message)
            console.log(err)
        })
    }
    getList = (val = '') => {
        // 人员查询
        let str = ``
        if (val) {
            str = `pageNum=1&pageSize=1000&userName=${val}`
        } else {
            str = `pageNum=1&pageSize=1000`
        }
        APIService.getUsers(str).then(res => {
            let personList = [];
            if (res.data.code === 200) {
                personList = res.data.data && res.data.data.data && res.data.data.data.length ? res.data.data.data : []
            }
            this.setState({ personList })
        })
    }
    kaidan = (record) => {
        let formDatapromise = { ...record }
        let empower = []
        if (formDatapromise?.empower) {
            // console.log('1', formDatapromise?.empower)
            let arr = formDatapromise.empower.split(',')
            empower = arr?.map(val => Number(val))
        } else {
            empower = []
        }
        formDatapromise.empower = empower
        // console.log(formDatapromise)
        this.setState({
            promiseView: true,
            formDatapromise
        })
    }
    openDetail = (record) => {
        // console.log(this.props)
        this.props.history.push({ pathname: "/agreement", data: record })
    }
    onHandleOk = () => {
        const { validateFields } = this.formDrawer;
        const { formData, operateType } = this.state;

        validateFields(async (err, values) => {
            if (!err) {
                this.setState({ loadingBtn: true })
                console.log('参数', values)
                values.creatorId = localStorage.getItem('userId')
                if (values?.acceptanceHopeTime) {
                    values.acceptanceHopeTime = values.acceptanceHopeTime.format('YYYY-MM-DD hh:mm:ss')
                } else {
                    values.acceptanceHopeTime = ''
                }
                if (operateType === 1) {

                    ApplyAcceptance.edit(values).then(res => {
                        if (res.data.code === 200) {
                            openModalMessage('success', res.data.msg)
                            this.fetch()
                            this.handleCancel()
                        } else {
                            openModalMessage('warning', res.data.msg)
                        }
                        this.setState({ loadingBtn: false })
                    }).catch(err => {
                        this.setState({ loadingBtn: false })
                    })
                } else {

                    ApplyAcceptance.add(values).then(res => {
                        if (res.data.code === 200) {
                            openModalMessage('success', res.data.msg)
                            this.fetch()
                            this.handleCancel()
                        } else {
                            openModalMessage('warning', res.data.msg)
                        }
                        this.setState({ loadingBtn: false })
                    }).catch(err => {
                        this.setState({ loadingBtn: false })
                    })
                }

            }
        })
    }

    onHandleOk1 = () => {
        const { validateFields } = this.formDrawer1;
        const { formData, operateType } = this.state;

        // validateFields(async (err, values) => {
        //     if (!err) {
        //         this.setState({ loadingBtn: true })
        //         console.log('参数', values)
        //         values.creatorId = localStorage.getItem('userId')


        //         ApplyAcceptance.adduploadImage(values).then(res => {
        //             if (res.data.code === 200) {
        //                 openModalMessage('success', res.data.msg)
        //                 this.fetch()
        //                 this.handleCancel1()
        //             } else {
        //                 openModalMessage('warning', res.data.msg)
        //             }
        //             this.setState({ loadingBtn: false })
        //         }).catch(err => {
        //             this.setState({ loadingBtn: false })
        //         })
        //     }
        // })
    }
    onpromiseOk = () => {
        const { validateFields } = this.promiseformDrawer;
        validateFields(async (err, values) => {
            if (!err) {
                this.setState({ loadingBtn: true })
                console.log('参数', values)
                values.updaterId = localStorage.getItem('userId')
                values.empower = values.empower.join(',')
                let params = { ...this.state.formDatapromise, ...values }
                ApplyAcceptance.empower(params).then(res => {
                    if (res.data.code === 200) {
                        openModalMessage('success', res.data.msg)
                        this.fetch()
                        this.promiseCancel()
                    } else {
                        openModalMessage('warning', res.data.msg)
                    }
                    this.setState({ loadingBtn: false })
                }).catch(err => {
                    this.setState({ loadingBtn: false })
                })


            }
        })
    }
    openTZJS = () => {
        const { selectedRowKeys, selectedRows } = this.state
        let str = ''
        if (selectedRowKeys.length !== 1) {
            openModalMessage('warning', '请选择一条数据');
            return
        } else {
            // str = selectedRowKeys.join(',')
        }
        console.log(selectedRows)
        let formData1 = { ...selectedRows[0] }
        this.setState({
            formData1,
            drawerVisible1: true
        })
    }

    openModel = (record, type) => {
        let drawerTitle = '新增'
        let formData = []
        let operateType = type
        if (type == 1) {
            drawerTitle = '修改'
            formData = record
            if (formData.acceptanceHopeTime) {
                formData.acceptanceHopeTime = moment(formData.acceptanceHopeTime)
            }
        }

        this.setState({
            drawerVisible: true,
            drawerTitle,
            formData,
            operateType
        })
    }
    handleCancel = e => {
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            drawerVisible: false,
        });
    };
    promiseCancel = e => {
        this.promiseformDrawer && this.promiseformDrawer.resetFields();
        this.setState({
            promiseView: false,
        });
    };
    handleCancel1 = e => {
        this.formDrawer1 && this.formDrawer1.resetFields();
        this.setState({
            drawerVisible1: false,
        });
    };
    handleSearch = value => {
        // console.log(value)
        this.setState({ searchItem: value }, () => { this.fetch() });

    };
    onHandleAdvanced = () => {
        this.setState({ advanced: !this.state.advanced })
    }
    loadData = (value, dataSource) => {
        console.log(value, dataSource)
    }
    deleteMul = () => {
        const { selectedRowKeys, selectedRows } = this.state
        let str = ''
        if (selectedRowKeys.length < 1) {
            openModalMessage('warning', '至少选择一条数据');
            return
        } else {
            str = selectedRowKeys.join(',')
        }

        let arr = selectedRows.filter(val => val.status !== 0)
        console.log(arr.length)
        if (arr.length > 0) {
            openModalMessage('warning', '只能输出新增状态数据');
        } else {
            this.remove(str)
        }
        // 

    }
    startWork = (type) => {
        const { selectedRowKeys } = this.state
        let str = ''
        if (selectedRowKeys.length < 1) {
            openModalMessage('warning', '至少选择一条数据');
            return
        } else {
            str = selectedRowKeys.join(',')
        }
        if (type == 0) { this.confirm(str) }

        if (type == 1) { this.rectification(str) }

    }
    rectification = (id) => {
        // const { searchItem } = this.state

        ApplyAcceptance.rectification(id).then(res => {
            if (res.data.code === 200) {
                openModalMessage('success', res.data.msg)
                this.fetch(this.state.pageNum, this.state.pageSize)
                this.handleCancel()
            } else {
                openModalMessage('warning', res.data.msg)
            }
            // this.setState({ loadingBtn: false })
        }).catch(err => {
            // this.setState({ loadingBtn: false })
            console.log(err.data.msg)
        })
    }
    confirm = (id) => {
        // const { searchItem } = this.state

        ApplyAcceptance.confirm(id).then(res => {
            if (res.data.code === 200) {
                openModalMessage('success', res.data.msg)
                this.fetch(this.state.pageNum, this.state.pageSize)
                this.handleCancel()
            } else {
                openModalMessage('warning', res.data.msg)
            }
            // this.setState({ loadingBtn: false })
        }).catch(err => {
            // this.setState({ loadingBtn: false })
            console.log(err.data.msg)
        })
    }
    remove = (id) => {
        // const { searchItem } = this.state
        const that = this
        confirm({
            title: '确定要删除数据吗？',
            // centered: true,
            // okText: '取消',
            // cancelText: '确定',
            onOk() {
                console.log('111111111')
                ApplyAcceptance.removeById(id).then(res => {
                    console.log('删除数据', res)
                    if (res.data.code === 200) {

                        that.fetch(that.state.pageNum, that.state.pageSize)
                        openModalMessage('success', res.data.msg)
                    } else {
                        openModalMessage('warning', res.data.msg)
                    }
                    // this.setState({ loadingBtn: false })
                }).catch(err => {
                    // this.setState({ loadingBtn: false })
                    // console.log(err.data.msg)
                    console.log(err)
                })
            },
            onCancel: async () => {
                console.log('Cancel')
            }
        });

    }
    onchangModel = (data) => {
        // console.log(data)
        this.setState({ visibleModel: true })
    }
    onDoubleClick = (record) => {
        let { formData } = this.state
        let productModel = record.id, productModelName = record.attributeFirst
        let formData1 = { productModel, productModelName }
        this.setState({ visibleModel: false, formData: { ...formData, ...formData1 } })
    }
    check = (record) => {
        this.setState({ checkVisible: true, checkRow: { ...record } })
    }
    checkCancel = () => {
        this.setState({ checkVisible: false })
    }

    checkSub = (type) => {
        const { checkRow } = this.state
        let status = 0
        if (type == 0) {
            status = 3
        } else {
            status = 2
        }
        let params = {
            ...checkRow,
            status
        }
        ApplyAcceptance.acceptanceCheck(params).then(res => {
            if (res.data.code === 200) {
                openModalMessage('success', res.data.msg)
                this.fetch(this.state.pageNum, this.state.pageSize)
                this.checkCancel()
            } else {
                openModalMessage('warning', res.data.msg)
            }
            // this.setState({ loadingBtn: false })
        }).catch(err => {
            // this.setState({ loadingBtn: false })
            console.log(err.data.msg)
        })
    }
    onHandleSearch = () => {
        console.log(this.props.form)
        let userName = this.props.form.getFieldValue('userName') || ''
        console.log('userName', userName)
        this.getList(userName)
    }

    saveFileList = (index, value) => {
        const { fileList } = this.state;
        fileList[index] = value;
        this.setState({ fileList })
        // console.log('这是什么', fileList)
    }
    render() {
        const { personList, promiseTitle, promiseView, drawerVisible1, drawerTitle1, formData1, selectedRowKeys, loading, dataSource, formData, drawerVisible, drawerTitle, advanced, columns, pageNum, pageSize, total } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log("selectedRowKeys", selectedRowKeys);
                console.log("selectedRows", selectedRows);
                this.setState({ selectedRowKeys, selectedRows })
            },
        }
        const { getFieldDecorator, setFieldsValue } = this.props.form;
        return (
            <div>

                <BasicLayoutSearch>
                    <SearchForm onSearch={this.handleSearch}
                        onClick={this.onHandleAdvanced}
                        advanced={advanced} />
                </BasicLayoutSearch>
                <BasicLayout
                    buttons={[
                        <CreateButton key='1' onClick={() => this.openModel([], 0)} icon="plus" />,
                        <DeleteButton key='2' onClick={this.deleteMul} icon="delete" />,
                        <CheckButton key='3' onClick={() => this.startWork(0)} icon="check" />,
                        <UploadButton key='4' onClick={() => this.openTZJS()} icon="upload" />,
                        <CloseButton key='5' onClick={() => { this.startWork(1) }} icon="minus" />,

                        // <Button key={10} type="primary" onClick={() => this.openModel([], 0)} icon="plus">新增</Button>,
                        //         // <Button key={0} type="primary" onClick={() => this.openModel(record, 0)} icon="plus">修改</Button>,
                        // <Button key={1} type="primary" onClick={this.deleteMul} icon="delete">删除</Button>,
                        // <Button key={2} onClick={() => this.startWork(0)} type="primary" icon="check">厂务部确认</Button>,
                        // <Button key={3} type="primary" onClick={() => this.openTZJS()} icon="upload">验收文档上传</Button>,
                        // <Button key={4} onClick={() => { this.startWork(1) }} type="primary" icon="minus">整改关闭</Button>,
                    ]}
                    name="客户验收申请"
                    icon="table">
                    <TableCustomize columns={columns} rowSelection={rowSelection} rowKey={(record) => record.id} dataSource={dataSource} pagination={false} loading={loading} allowDrafting={true} allowRowEdit allowEditable={this.loadData} />
                    <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                </BasicLayout>
                {/* 验收 */}
                <Modal
                    width='600px'
                    title='验收'
                    visible={this.state.checkVisible}
                    centered
                    footer={null}
                    // onOk={this.submit}
                    onCancel={this.checkCancel}
                // okText="保存"
                // cancelText="取消"
                >
                    <div>
                        <div style={{ fontSize: '24px', textAlign: 'center' }}>请确认此设备是否验收合格</div>
                        <div style={{ display: 'flex', justifyContent: 'center', marginTop: '40px' }}>
                            <div onClick={() => this.checkSub(0)} style={{ width: '100px', height: '100px', background: '#95F204', lineHeight: '100px', textAlign: 'center' }}>验收合格</div>
                            <div onClick={() => this.checkSub(1)} style={{ width: '100px', height: '100px', background: '#D7D7D7', lineHeight: '100px', textAlign: 'center', marginLeft: '40px' }}>验收不合格</div>
                        </div>
                    </div>
                </Modal>
                {/* 授权账号 */}
                <Drawer width={400} visible={promiseView} title={promiseTitle} onClose={this.promiseCancel}>
                    <Form className="search-form">
                        <Row gutter={24}>
                            <Col span={14}>
                                <FormItem label='姓名'>
                                    {getFieldDecorator('userName')(
                                        <Input placeholder={'请输入姓名'} allowClear />
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={4}>
                                <FormItem>
                                    <Button type="primary" icon="search" onClick={this.onHandleSearch}>
                                        查询
                                    </Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <AddFormPromise
                        formData={this.state.formDatapromise}
                        onOk={this.onpromiseOk}
                        ref={node => (this.promiseformDrawer = node)}
                        onClose={this.promiseCancel}
                        operateType={this.state.operateType}
                        personList={this.state.personList}
                    // onchangModel={this.onchangModel}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.promiseCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onpromiseOk}>
                            {'确认'}
                        </Button>
                    </div>
                </Drawer>

                {/* 新增修改 */}
                <Drawer width={400} visible={drawerVisible} title={drawerTitle} onClose={this.handleCancel}>
                    <AddForm
                        formData={formData}
                        onOk={this.onHandleOk}
                        ref={node => (this.formDrawer = node)}
                        onClose={this.handleCancel}
                        operateType={this.state.operateType}
                        ModelList={this.state.ModelList}
                        onchangModel={this.onchangModel}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk}>
                            {'确认'}
                        </Button>
                    </div>
                </Drawer>

                {/* 验收文档上传 */}
                <Drawer width={400} visible={drawerVisible1} title={drawerTitle1} onClose={this.handleCancel1}>
                    <AddForm2
                        formData={formData1}
                        onOk={this.onHandleOk1}
                        ref={node => (this.formDrawer1 = node)}
                        onClose={this.handleCancel1}
                        // operateType={this.state.operateType}
                        ModelList={this.state.ModelList}
                        onchangModel={this.onchangModel}
                        saveFileList={this.saveFileList}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel1} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk1}>
                            {'确认'}
                        </Button>
                    </div>
                </Drawer>


                <Modal
                    width='600px'
                    title='机型'
                    visible={this.state.visibleModel}
                    centered
                    footer={null}
                    // onOk={this.submit}
                    onCancel={() => this.setState({ visibleModel: false })}
                // okText="保存"
                // cancelText="取消"
                >

                    <BasicLayout
                        name={`机型`}
                        icon="table"
                        buttons={[
                            // <Button key={4} buttonName='导入' apiPath={`${requestPrefixProcess}/spsMaterialInspectionStandard/importExcel`} parameter={{ userId: userId }} load={true} fetch={() => this.fetch({ ...queryCondition })} />,
                            // <Button key={3} fileName='工装信息配置' buttonName='模板导出' method='post' apiPath={`${requestPrefixProcess}/spsMaterialInspectionStandard/exportExcel`} data={queryCondition} />,
                        ]}

                    >
                        <Table
                            columns={this.state.columnsModel}
                            rowKey={(record) => record.id}
                            dataSource={this.state.ModelList}
                            pagination={false}
                            loading={false}
                            allowDrafting={false}
                            scroll={{ x: 'auto' }}
                            onRow={record => {
                                return {
                                    onDoubleClick: event => { this.onDoubleClick(record) },
                                };
                            }}
                        />
                        <BasicPagination
                            pageNum={this.state.pagination.pageNum}
                            pageSize={this.state.pagination.pageSize}
                            total={this.state.model_total}
                            // queryCondition={queryCondition}
                            loadData={this.queryCondition} />
                    </BasicLayout>
                </Modal>
            </div >
        );
    }
}
export default Form.create()(withRouter(Apply));